package sz.szsmk.citizencard.ui.newversion.fragment

import android.app.Service
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Vibrator
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import kotlinx.android.synthetic.main.fragment_paycode.*
import kotlinx.android.synthetic.main.layout_paycode_description.*
import kotlinx.android.synthetic.main.layout_paycode_noenoughmoney.*
import kotlinx.android.synthetic.main.layout_paycode_notauth.*
import kotlinx.android.synthetic.main.layout_paycode_qrcode.*
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.R
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.bean.response.CakeBalanceBeanRes
import sz.szsmk.citizencard.model.network.bean.response.CakeQRBeanRes
import sz.szsmk.citizencard.model.network.bean.response.CheckVirCakeBeanRes
import sz.szsmk.citizencard.mvp.BasePresenter
import sz.szsmk.citizencard.ui.dzsmkfragment.AppBaseFragment
import sz.szsmk.citizencard.ui.newversion.fragment.presenter.PayCodePresenter
import sz.szsmk.citizencard.ui.newversion.fragment.view.PayCodeMvpView
import sz.szsmk.citizencard.util.*
import java.math.BigDecimal
import javax.inject.Inject

/**
 *  author : hyt
 *  date : 2020/10/14
 *  description :
 */
class PayCodeFragment: AppBaseFragment() , PayCodeMvpView {

    @Inject
    lateinit var payCodePresenter: PayCodePresenter

    override fun initPresenters(): Array<BasePresenter<*>>? {
        return arrayOf(payCodePresenter)
    }

    override fun getTopTitle() = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_paycode, container, false)
        component.inject(this)
        return root
    }
    var mVibrator: Vibrator ?=null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //振动器
        mVibrator = activity?.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator?

        if (ermCountDownTimer == null) {
            ermCountDownTimer = object : CountDownTimer(3 * 1000, 1000) {
                override fun onTick(l: Long) {}
                override fun onFinish() {
                    lin_refresh.isEnabled = true
                    iv_payCode.isEnabled = true
                    refresh_icon.setImageResource(R.mipmap.icon_refresh)
                    refresh_state.text = "请点击二维码刷新"
                    autoRefreshCountDownTimer!!.start()
                }
            }
        }
        if (autoRefreshCountDownTimer == null) {
            autoRefreshCountDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(l: Long) {}
                override fun onFinish() {
                    lin_refresh.isEnabled = false
                    iv_payCode.setEnabled(false)
                    refresh_icon.setImageResource(R.drawable.adress_check)
                    refresh_state.text = "已刷新"
                    if (ermCountDownTimer != null) {
                        ermCountDownTimer?.start()
                        mVibrator?.vibrate(1000)
                    }
                }
            }
        }

    }

    override fun onResume() {
        super.onResume()

        layout_paycode_notauth.visibility = View.GONE
        layout_paycode_noenoughmoney.visibility = View.GONE
        layout_paycode_qrcode.visibility = View.GONE

        payCodePresenter.getIsOpenPayCode()

        //重新计时
        if (isAutoStart) {
            ermCountDownTimer?.start()
        }
    }

    var iseyeCheck = true


    override fun getIsOpenPayCodeSuccess(response: CheckVirCakeBeanRes) {
        if (response.exist == 1) {
            //已经开通
            coakeCode = response.cardNo

            //打开二维码
            layout_paycode_qrcode.visibility = View.VISIBLE
            //打开描述
            layout_paycode_description.visibility = View.VISIBLE

            //获取金额
            payCodePresenter.queryCakeBalance(response.cardNo)

            tv_cardNumber.text = "卡号：" + response.cardNo

            iv_eyeState.setOnClickListener {
                if (iseyeCheck) {
                    tv_cardNumber.text = "卡号：*************"
                } else {
                    tv_cardNumber.text = "卡号：$coakeCode"
                }
                iseyeCheck = !iseyeCheck
            }

            tv_transactions.setOnClickListener {
                //交易记录
                var bundle = Bundle()
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/transactions?cardNo=" + coakeCode)
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }

            tv_recharge.setOnClickListener {
                //充值
                var bundle = Bundle()
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/recharge?access_token=" +
                        ACache.get(DaggerApplication.getIns()).getAsString("access_token"))
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }

        } else {
            layout_paycode_notauth.visibility = View.VISIBLE
            btn_openPayCode.setOnClickListener {
                //跳转h5 授权
                val bundle = Bundle()
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/explain?access_token=" +
                        ACache.get(DaggerApplication.getIns()).getAsString("access_token"))
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }
        }
    }

    var bignum4: BigDecimal? = null
    //蛋糕卡 卡号
    var coakeCode = ""

    @RequiresApi(api = Build.VERSION_CODES.N)
    override fun queryCakeBalanceSuccess(response: CakeBalanceBeanRes) {
        //获取余额
        val bignum1: BigDecimal = BigDecimal(response.cakeBalance)
        val bignum3 = bignum1.divide(BigDecimal(100))
        bignum4 = bignum3.setScale(2)

        if(bignum4?.compareTo(BigDecimal.ZERO)==0 ){
            //余额不足
            layout_paycode_noenoughmoney.visibility = View.VISIBLE
            immediatelyRecharge.setOnClickListener {
                //充值
                var bundle = Bundle()
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/mdlPages/recharge?access_token=" +
                        ACache.get(DaggerApplication.getIns()).getAsString("access_token"))
                JumpUtils.jumptoNatvie(context, "webView", 0, bundle)
            }
        }else{
            tv_cakeMoney.text = Html.fromHtml("<font color='#414861'>余额 </font><font color='#FD6B3B'>${bignum4.toString()}元</font>", Html.FROM_HTML_MODE_LEGACY)

            payCodePresenter.getPayCode(coakeCode)

        }
    }

    var isAutoStart = false

    override fun onPayCodeSuccess(response: CakeQRBeanRes) {

        //支付码 返回
        if (!StringUtils.isBlank(response.markCode)) {
            iv_payCode.post {
                val width: Int = iv_payCode.measuredWidth
                try {
                    response.markCode
                    val qrCodeImg = QrCodeUtils.createQRCode(response.markCode, width)
                    iv_payCode.setImageBitmap(qrCodeImg)
                    refresh_icon.setImageResource(R.drawable.adress_check)
                    refresh_state.text = "已刷新"
                    if (ermCountDownTimer != null) {
                        isAutoStart = true
                        ermCountDownTimer?.start()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        lin_refresh.setOnClickListener {
            payCodePresenter.getPayCode(coakeCode)
            if (ermCountDownTimer != null) {
                ermCountDownTimer!!.start()
            }

            lin_refresh.isEnabled = false
            iv_payCode.isEnabled = false
            autoRefreshCountDownTimer!!.cancel()

        }
    }

    override fun onFail(baseBean: BaseBean) {
       showToast(baseBean.message)
    }

    private var ermCountDownTimer: CountDownTimer? = null
    private var autoRefreshCountDownTimer: CountDownTimer? = null


    override fun onPause() {
        super.onPause()

        if (ermCountDownTimer != null) {
            ermCountDownTimer?.cancel()
        }
        if (autoRefreshCountDownTimer != null) {
            autoRefreshCountDownTimer?.cancel()
        }
        if (null != mVibrator) {
            mVibrator?.cancel()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        if (null != mVibrator) {
            mVibrator?.cancel()
            mVibrator = null
        }

    }
}